package com.gxan.web.controller;
import com.gxan.utils.GenerateSequenceUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("111");
        //1.创建文件上传工厂对象
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        //2.创建文件上传的组件
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        //3.设置文件上传的编码
        servletFileUpload.setHeaderEncoding("UTF-8");

        try {
            //4.获取请求对象塞入到上传组件中
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);
            //5.fileItems得到的表单对象，封装一个一个的FileItem
            //5.1循环得到表单元素
            for (FileItem fileItem : fileItems) {
                //5.2判断是一个普通的表单元素还是文件上传元素
                if(fileItem.isFormField()){//普通的表单元素
                    System.out.println(fileItem.getFieldName());//键
                    System.out.println(fileItem.getString());//值
                }else {//文件上传元素
                    //获取字节输入流
                    InputStream is = fileItem.getInputStream();
                    //源文件名称
                    String sourcefileName = fileItem.getName();
                    //保存在本地项目目录中
                    //获取当前项目路径E： F：
                    String uploadDistPath = request.getRealPath("/");
                    //上传文件名称(Random/UUID+毫秒数值)：和源文件名称不能一致，如果一致就覆盖
                    //生成唯一的文件名称
                    String fileName = GenerateSequenceUtil.generateSequenceNo();
                    //截取源文件图片的后缀
                    String ext = sourcefileName.substring(sourcefileName.lastIndexOf("."));
                    //目标文件名称
                    String targetFileName = fileName+ext;
                    //目标文件保存路径
                    String filePath = File.separator + "upload"+File.separator;
                    //判断路径是否存在:项目路径
                    File file = new File(uploadDistPath+filePath);
                    if(!file.exists()){//如果没有此路径，把目录创建
                        file.mkdirs();
                    }

                    //6.将图片的相对路径保存下来，将来存入到数据库中

                    String targetDataBasePath = filePath + targetFileName;

                    //7.创建输出流：实现文件上传的功能
                    OutputStream os = new FileOutputStream(file+File.separator+targetFileName);
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len=is.read(bytes))!=-1){
                        os.write(bytes,0,len);
                    }

                    os.flush();
                    os.close();
                    is.close();

                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }


    }
}
